import * as dotenv from 'dotenv'
import express from 'express'

dotenv.config({
  path: ['.env.local', '.env']
})

const openaiApiKey = process.env.VITE_DEEPSEEK_API_KEY

const app = express()
const port = 3000
const endpoint = 'https://api.deepseek.com/v1/chat/completions'

// SSE 端点
app.get('/stream', async(req, res) => {
  res.setHeader('Content-Type', 'text/event-stream')
  res.setHeader('Cache-Control', 'no-cache')
  res.setHeader('Connection', 'keep-alive')
  res.setHeader('Access-Control-Allow-Origin', '*')
  res.flushHeaders()  // 立即发送头信息

  try {
    // 发送 OPENAI 请求
    const response = await fetch(endpoint, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${openaiApiKey}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        model: 'deepseek-chat',
        messages: [{role: 'user', content: req.query.question}],
        stream: true
      })
    })

    if (!response.ok) {
      throw new Error('Network response was not ok')
    }
    const reader = response.body.getReader()
    const decoder = new TextDecoder()
    let done = false
    let buffer = ''
    while (!done) {
      const {value, done: doneReading} = await reader.read()
      done = doneReading
      const chunkValue = buffer + decoder.decode(value)
      buffer = ''

      // 处理每个完整的 JSON 对象
      const lines = chunkValue.split('\n').filter(line => line.trim() && line.startsWith('data: '));
      for (const line of lines) {
        const incoming = line.slice(6)
        if (incoming === '[DONE]') {
          done = true
          break
        }
        try {
          const data = JSON.parse(incoming)
          const delta = data.choices[0].delta.content
          if (delta) {
            res.write(`data: ${delta}\n\n`)  // 发送数据到客户端
          }
        } catch (error) {
          buffer += incoming
        }
      }
    }

    res.write('event: end\n')  // 发送结束事件
    res.write('data: [DONE]\n\n')  // 通知客户端数据流结束
    res.end()  // 关闭连接

  } catch (err) {
    console.error('Error:', err)
  }

})

app.listen(port, () => {
  console.log('server is running on port 3000');
})